from sqlalchemy import Column, Integer, String, ForeignKey, Table, text, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.sql.elements import and_

from conf.mysql_cnx import MysqlCnxPool

Base = declarative_base()


class DcmDownload(Base):
    __tablename__ = 'dcm_download'
    id = Column(Integer, primary_key=True)

    study_uid = Column(String)
    status = Column(Integer)

    finding = Column('exam_finding', String)
    impression = Column(String)

    body_part = Column('exam_body_part', String)
    modality = Column(String)
    create_time = Column('add_time', DateTime)


class DcmDownloadStatus:
    IDLE = 0
    COMPLETED = 2


def find_dcm_download_list(keyword, status, page_size, page_num):
    session = MysqlCnxPool().get_session()

    filters = [DcmDownload.status == status]
    if keyword is not None:
        filters.append(DcmDownload.finding.contains(keyword))

    data_list = session.query(DcmDownload) \
        .filter(*filters) \
        .offset((page_num - 1) * page_size).limit(page_size).all()

    total = session.query(DcmDownload).filter(*filters).count()

    return data_list, total


if __name__ == '__main__':
    find_dcm_download_list(None, DcmDownloadStatus.COMPLETED, 10, 1)
